package club.babyf.nativeai.demo.algorithm;

/**
 * _17_HasCyclic.
 *
 * @author zhanglei.
 * @date 2025/7/20 18:20.
 * @description 检测链表是否有环.
 */
public class _17_HasCyclic {

    public boolean hasCyclic(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }

        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return true;
            }
        }

        return false;
    }

    public static class ListNode {

        int value;

        ListNode next;

        public ListNode(int value) {
            this.value = value;
        }

        public ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.value);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

    public static void main(String[] args) {
        _17_HasCyclic hasCyclic = new _17_HasCyclic();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(head);
        ListNode temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = head;
        boolean b = hasCyclic.hasCyclic(head);
        System.out.println(b);
    }

}
